package logic

import (
	"cloud-disk/core/helper"
	"cloud-disk/core/internal/svc"
	"cloud-disk/core/internal/types"
	"cloud-disk/core/model"
	"cloud-disk/tool"
	"context"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserRegisterLogic) UserRegister(req *types.UserRegisterRequest) (resp *types.UserRegisterSendResponse, err error) {
	code, ok := tool.Cache.Get(req.VerifyKey)
	resp = new(types.UserRegisterSendResponse)
	if !ok {
		resp.Message = "验证码错误，请重新发送验证码"
		resp.Code = 100
		return resp, nil
	}

	if code != req.Code {
		resp.Message = "验证码错误，请重新输入"
		resp.Code = 100
		return resp, nil
	}

	count, err := l.svcCtx.UserModel.GetUserCountByName(req.Name)
	if err != nil {
		resp.Message = "注册失败，请稍后重试"
		resp.Code = 100
		return resp, nil
	}
	if count != 0 {
		resp.Message = "该用户已存在，请重新输入"
		resp.Code = 100
		return resp, nil
	}

	user := model.UserBasic{
		Identity: helper.GetUUID(),
		Name:     req.Name,
		Password: helper.Md5(req.Password),
		Email:    req.Email,
	}

	err = l.svcCtx.UserModel.CreateUser(&user)
	if err != nil {
		resp.Message = "注册失败，请稍后重试" + err.Error()
		resp.Code = 100
		return resp, nil
	}

	tool.Cache.Delete(req.VerifyKey)
	resp.Message = "注册成功"
	resp.Code = 200
	return resp, nil
}
